package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 鬼谷登录方面
 *
 * @author ym
 * @date 2025/06/27 19:10
 */
@Aspect
@Component
@Slf4j
public class GuiGuLoginAspect {
    /**
     * redis模板
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 切口
     *
     * @param guiGuLogin gui gu login
     */
    @Pointcut("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(guiGuLogin)")
    public void pointCut(GuiGuLogin guiGuLogin) {
    }

    /**
     * 登录方面
     *
     * @param joinPoint  连接点
     * @param guiGuLogin gui gu login
     * @return {@link Object}
     * @throws Throwable 对象
     */
    @Around(value = "pointCut(guiGuLogin)", argNames = "joinPoint,guiGuLogin")
    public Object loginAspect(ProceedingJoinPoint joinPoint, GuiGuLogin guiGuLogin) throws Throwable {
        Object resultObject = new Object();
        log.info("前置通知...");
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("token");
        String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(loginKey);
        if (userInfoVo == null && guiGuLogin.required()) {
            log.info("用户未登录");
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);

        }
        if (userInfoVo != null) {

            AuthContextHolder.setUserId(userInfoVo.getId());//设置用户id

        }
        resultObject = joinPoint.proceed();//执行方法
        AuthContextHolder.removeUserId();//移除用户id防止影响其他请求

        return resultObject;

    }

}
